package com.landscope.central.service.api;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.landscope.central.controller.api.dto.ApiProjectDto;
import com.landscope.central.controller.api.dto.AuthorizeDto;
import com.landscope.central.controller.api.param.ApiUserAuthorizeParam;
import com.landscope.central.controller.base.ResponseResult;
import com.landscope.central.entity.Role;
import com.landscope.central.entity.User;
import com.landscope.central.exception.BizException;
import com.landscope.central.exception.E_EXCEPTION_TYPE;
import com.landscope.central.mapper.ProjectMapper;
import com.landscope.central.mapper.RoleMapper;
import com.landscope.central.mapper.UserMapper;
import com.landscope.central.render.Result;
import com.landscope.central.utils.PasswordUtil;
import com.landscope.central.utils.TokenUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务
 *
 * @author qzp
 * @version v1.0
 * @date 2021/6/28 14:37
 **/
@Service
public class ApiUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 用户授权服务
     *
     * @param param:
     * @return {@link * @return java.lang.Object}
     * @throws
     * @author 瞿子朋
     * @date 2021/6/28 14:39
     * @version v1.0
     **/
    public ResponseResult authorize(ApiUserAuthorizeParam param) {
        // 验证账号
        Optional<User> user = userMapper.findByAccount(param.getAccount());
        user.orElseThrow(() -> BizException.fail(E_EXCEPTION_TYPE.user_nonexistent)); // 账号不存异常

        if (!user.get().getPassword().equals(PasswordUtil.encrypt(param.getPassword())))
            throw BizException.fail(E_EXCEPTION_TYPE.user_wrong_password); // 密码错误异常

        if (user.get().getEnabled() == 0)
            throw BizException.fail(E_EXCEPTION_TYPE.user_disable); // 用户被禁用异常

        // 获取项目列表
        String[] codes = user.get().getManageProjectCodes().split(";");
        List<ApiProjectDto> projectList = projectMapper.findByCodes(codes);

//        // 将项目重新组装为，子系统-》项目 目录的树形结构
//        JSONArray subSystemList = new JSONArray();
//        for (ApiProjectDto dto : projectList) {
//            boolean has = false;
//            for (int i = 0; i < subSystemList.size(); i++) {
//                JSONObject subSystem = subSystemList.getJSONObject(i);
//                if (subSystem.getStr("code").equals(dto.getSubSystemCode())) {
//                    has = true;
//
//                    JSONArray projectArray = subSystem.getJSONArray("projectList");
//                    JSONObject project = new JSONObject();
//                    project.put("code", dto.getCode());
//                    project.put("name", dto.getName());
//                    project.put("description", dto.getDescription());
//                    project.put("latitude", dto.getLatitude());
//                    project.put("longitude", dto.getLongitude());
//                    project.put("projectMap", dto.getProjectMap());
//                    projectArray.add(project);
//                    subSystem.put("projectList", projectArray);
//                    break;
//                }
//            }
//            if (!has) {
//                JSONObject subSystem = new JSONObject();
//                subSystem.put("code", dto.getSubSystemCode());
//                subSystem.put("name", dto.getSubSystemName());
//                subSystem.put("description", dto.getSubSystemDescription());
//                subSystem.put("ip", dto.getIp());
//                subSystem.put("dataPort", dto.getDataPort());
//
//                JSONArray projectArray = new JSONArray();
//                JSONObject project = new JSONObject();
//                project.put("code", dto.getCode());
//                project.put("name", dto.getName());
//                project.put("description", dto.getDescription());
//                project.put("latitude", dto.getLatitude());
//                project.put("longitude", dto.getLongitude());
//                project.put("projectMap", dto.getProjectMap());
//                projectArray.add(project);
//                subSystem.put("projectList", projectArray);
//
//                subSystemList.add(subSystem);
//            }
//        }

        JSONArray jsonArray = new JSONArray();
        for (ApiProjectDto dto : projectList) {
            String url = dto.getIp() + ":" + dto.getDataPort();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", dto.getName());
            jsonObject.put("code", dto.getCode());
            jsonObject.put("ip", url);
            jsonArray.add(jsonObject);
        }

        Role role = roleMapper.findByCode(user.get().getRoleCode());

        // 生成令牌
        String access_token = TokenUtil.createUserAccessToken(user.get(), projectList, role.getPermissionCode());

        return new ResponseResult().success().setData(new AuthorizeDto(access_token, projectList));
    }
}
